import React, { useState, useRef } from 'react';
import { Form, Input, Button, Typography, Spin, message, Card, Row, Col, Select, Tabs, Space } from 'antd';
import { CopyOutlined, ArrowRightOutlined, RedoOutlined } from '@ant-design/icons';
import type { InputNumberProps } from 'antd';
import InputNumber from 'antd/es/input-number';
import CommonTour, { TourGuideButton } from '@/components/CommonTour';

const { Title, Paragraph } = Typography;
const { TextArea } = Input;
const { Option } = Select;
const { TabPane } = Tabs;

/**
 * 文章改写功能
 * 对现有文章进行重写，保持原意但改变表达方式
 */
const ArticleRewritingPage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [rewrittenContent, setRewrittenContent] = useState<string>('');
  const [rewritingStyle, setRewritingStyle] = useState<string>('professional');
  const [rewritingLevel, setRewritingLevel] = useState<number>(2);
  const [rewritingHistory, setRewritingHistory] = useState<string[]>([]);
  const [tourVisible, setTourVisible] = useState<boolean>(false);

  // 创建ref引用
  const originalContentRef = useRef<HTMLDivElement>(null);
  const styleRef = useRef<HTMLDivElement>(null);
  const levelRef = useRef<HTMLDivElement>(null);
  const rewriteButtonRef = useRef<HTMLDivElement>(null);
  const resultRef = useRef<HTMLDivElement>(null);
  const historyRef = useRef<HTMLDivElement>(null);

  // 组织ref引用
  const tourRefs = {
    originalContent: originalContentRef,
    style: styleRef,
    level: levelRef,
    rewriteButton: rewriteButtonRef,
    result: resultRef,
    history: historyRef
  };

  // 定义steps配置
  const tourSteps = [
    {
      key: 'originalContent',
      title: '输入原文内容',
      description: '请在文本框中输入需要改写的文章内容',
    },
    {
      key: 'style',
      title: '选择改写风格',
      description: '根据需要选择合适的改写风格，如专业严谨、通俗易懂等',
    },
    {
      key: 'level',
      title: '设置改写程度',
      description: '调整改写的程度，从1到5，数字越大改写幅度越大',
    },
    {
      key: 'rewriteButton',
      title: '开始改写',
      description: '点击按钮开始AI文章改写过程',
    },
    {
      key: 'result',
      title: '查看改写结果',
      description: '改写完成后，您可以在此处查看和复制改写后的内容',
    },
    {
      key: 'history',
      title: '改写历史',
      description: '点击此处查看之前的改写历史记录',
    },
  ];

  // 显示引导
  const showTour = () => {
    // 延迟显示，确保DOM已经渲染
    setTimeout(() => {
      setTourVisible(true);
    }, 100);
  };

  // 改写风格选项
  const rewritingStyles = [
    { value: 'professional', label: '专业严谨', description: '适合学术或专业场合的正式表达' },
    { value: 'casual', label: '通俗易懂', description: '口语化表达，简单易懂' },
    { value: 'storytelling', label: '故事化', description: '富有叙事性，引人入胜' },
    { value: 'persuasive', label: '说服力', description: '增强观点说服力和感染力' },
    { value: 'creative', label: '创意表达', description: '新颖独特的表达方式' },
    { value: 'concise', label: '简洁精炼', description: '精简内容，保留核心信息' },
  ];

  // 处理改写风格变化
  const handleStyleChange = (value: string) => {
    setRewritingStyle(value);
  };

  // 处理改写程度变化
  const handleLevelChange = (value?: any) => {
    if (value !== undefined) {
      setRewritingLevel(value);
    }
  };

  // 处理表单提交，进行文章改写
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const originalContent = values.originalContent || '';

      if (!originalContent.trim()) {
        message.warning('请输入需要改写的文章内容');
        return;
      }

      setLoading(true);
      setRewrittenContent('');

      // 模拟API调用延迟
      setTimeout(() => {
        const rewritten = rewriteArticle(originalContent, rewritingStyle, rewritingLevel);
        setRewrittenContent(rewritten);
        // 保存到历史记录
        if (rewritingHistory.length >= 5) {
          setRewritingHistory([...rewritingHistory.slice(1), rewritten]);
        } else {
          setRewritingHistory([...rewritingHistory, rewritten]);
        }
        setLoading(false);
        message.success('文章改写成功！');
      }, 2000);
    } catch (error) {
      setLoading(false);
      message.error('改写失败，请重试');
    }
  };

  // 重新改写
  const handleRewriteAgain = () => {
    if (!rewrittenContent) {
      message.warning('请先生成改写内容');
      return;
    }

    setLoading(true);

    // 模拟API调用延迟
    setTimeout(() => {
      const values = form.getFieldsValue();
      const originalContent = values.originalContent || '';
      const rewritten = rewriteArticle(originalContent, rewritingStyle, rewritingLevel);
      setRewrittenContent(rewritten);
      // 保存到历史记录
      if (rewritingHistory.length >= 5) {
        setRewritingHistory([...rewritingHistory.slice(1), rewritten]);
      } else {
        setRewritingHistory([...rewritingHistory, rewritten]);
      }
      setLoading(false);
      message.success('重新改写成功！');
    }, 2000);
  };

  // 复制改写内容
  const handleCopyContent = (content: string) => {
    navigator.clipboard.writeText(content).then(() => {
      message.success('内容已复制到剪贴板');
    }).catch(() => {
      message.error('复制失败，请手动复制');
    });
  };

  // 使用历史记录中的内容
  const handleUseHistory = (content: string) => {
    setRewrittenContent(content);
    message.success('已使用历史改写内容');
  };

  // 文章改写的模拟函数
  const rewriteArticle = (content: string, style: string, level: number): string => {
    // 这里是模拟文章改写的逻辑，实际应用中应该调用AI模型

    // 根据改写风格和程度生成不同的改写内容
    const styleRewriters: Record<string, (c: string, l: number) => string> = {
      'professional': (c, l) => {
        // 专业严谨风格的改写
        const replacements: Record<string, string> = {
          '我们': '本研究团队',
          '非常': '显著',
          '很多': '大量',
          '简单': '简易',
          '重要': '关键',
          '好': '优良',
          '结果': '研究成果',
          '表明': '显示',
          '发现': '揭示',
          '研究': '系统性研究',
        };

        let rewritten = c;
        Object.entries(replacements).forEach(([key, value]) => {
          const regex = new RegExp(key, 'g');
          rewritten = rewritten.replace(regex, value);
        });

        // 根据改写程度增加更多专业术语
        if (level > 2) {
          rewritten = rewritten.replace(/研究成果/g, '实证研究结果');
          rewritten = rewritten.replace(/显示/g, '明确显示');
          rewritten = rewritten.replace(/系统性研究/g, '多维度系统性研究');
        }

        return rewritten;
      },
      'casual': (c, l) => {
        // 通俗易懂风格的改写
        const replacements: Record<string, string> = {
          '因此': '所以',
          '然而': '不过',
          '例如': '比如',
          '总的来说': '总的来说',
          '分析表明': '看起来',
          '进行研究': 'founded发现',
          '重要因素': '关键原因',
          '影响因素': '影响原因',
          '提高效率': '效率更高',
        };

        let rewritten = c;
        Object.entries(replacements).forEach(([key, value]) => {
          const regex = new RegExp(key, 'g');
          rewritten = rewritten.replace(regex, value);
        });

        // 根据改写程度增加更多口语化表达
        if (level > 2) {
          rewritten = rewritten.replace(/founded发现/g, '我们发现');
          rewritten = rewritten.replace(/效率更高/g, '效率变得更高');
          rewritten = rewritten.replace(/关键原因/g, '最主要的原因');
        }

        return rewritten;
      },
      'storytelling': (c, l) => {
        // 故事化风格的改写
        const startPhrases = [
          '让我来给你讲一个关于...',
          '曾经有一个...',
          '在很久很久以前...',
          '想象一下...',
          '这是一个关于...的故事',
        ];

        const endPhrases = [
          '这就是为什么...',
          '从这个故事中我们可以学到...',
          '最终...',
          '通过这个经历...',
          '这告诉我们...',
        ];

        const randomStart = startPhrases[Math.floor(Math.random() * startPhrases.length)];
        const randomEnd = endPhrases[Math.floor(Math.random() * endPhrases.length)];

        let rewritten = `${randomStart}\n${c}\n${randomEnd}`;

        // 根据改写程度增加更多故事元素
        if (level > 2) {
          rewritten = rewritten.replace(/研究/g, '探索之旅');
          rewritten = rewritten.replace(/发现/g, '惊人发现');
          rewritten = rewritten.replace(/分析/g, '深入分析');
        }

        return rewritten;
      },
      'persuasive': (c, l) => {
        // 说服力风格的改写
        const powerWords = [
          '毫无疑问',
          '重要的是',
          '必须承认',
          '显而易见',
          '值得注意的是',
          '事实上',
          '显然',
          '确实',
        ];

        let rewritten = c;

        // 在句子开头添加有说服力的词汇
        const sentences = rewritten.split('. ');
        const powerfulSentences = sentences.map((sentence, index) => {
          if (index % 3 === 0 && sentence) {
            const randomWord = powerWords[Math.floor(Math.random() * powerWords.length)];
            return `${randomWord}，${sentence.charAt(0).toLowerCase() + sentence.slice(1)}`;
          }
          return sentence;
        });

        rewritten = powerfulSentences.join('. ');

        // 根据改写程度加强语气
        if (level > 2) {
          rewritten = rewritten.replace(/可以/g, '完全可以');
          rewritten = rewritten.replace(/应该/g, '必须');
          rewritten = rewritten.replace(/重要/g, '至关重要');
        }

        return rewritten;
      },
      'creative': (c, l) => {
        // 创意表达风格的改写
        const metaphors = [
          '像...一样',
          '如同...',
          '仿佛...',
          '宛如...',
          '好比...',
        ];

        let rewritten = c;

        // 随机添加比喻
        const wordsToMetaphorize = ['快速', '重要', '复杂', '简单', '有效'];
        wordsToMetaphorize.forEach(word => {
          const regex = new RegExp(word, 'g');
          rewritten = rewritten.replace(regex, () => {
            const randomMetaphor = metaphors[Math.floor(Math.random() * metaphors.length)];
            return `${word}${randomMetaphor}`;
          });
        });

        // 根据改写程度增加更多创意元素
        if (level > 2) {
          rewritten = rewritten.replace(/研究/g, '智力探险');
          rewritten = rewritten.replace(/发现/g, '灵感闪现');
          rewritten = rewritten.replace(/分析/g, '思维解剖');
        }

        return rewritten;
      },
      'concise': (c, l) => {
        // 简洁精炼风格的改写
        const redundantPhrases: Record<string, string> = {
          '在我看来': '我认为',
          '非常重要': '重要',
          '在很大程度上': '很大程度上',
          '由于这个原因': '因此',
          '我们可以看到': '可见',
          '需要指出的是': '值得注意的是',
          '总的来说': '总之',
          '实际上': '事实上',
        };

        let rewritten = c;
        Object.entries(redundantPhrases).forEach(([key, value]) => {
          const regex = new RegExp(key, 'g');
          rewritten = rewritten.replace(regex, value);
        });

        // 根据改写程度进一步精简
        if (level > 2) {
          rewritten = rewritten.replace(/值得注意的是/g, '注意');
          rewritten = rewritten.replace(/很大/g, '很大');
          rewritten = rewritten.replace(/我认为/g, '我想');
        }

        return rewritten;
      },
    };

    const rewriter = styleRewriters[style] || styleRewriters.professional;
    return rewriter(content, level);
  };

  // 获取当前选择的改写风格描述
  const getSelectedStyleDescription = (): string => {
    const selectedStyle = rewritingStyles.find(s => s.value === rewritingStyle);
    return selectedStyle ? selectedStyle.description : '';
  };

  // 获取改写程度的描述
  const getLevelDescription = (): string => {
    const descriptions = [
      '保留原意，轻微调整',
      '适当改写，保持结构',
      '大幅改写，变换句式',
      '完全重写，仅保留核心',
      '创新表达，个性化改编',
    ];

    return descriptions[rewritingLevel - 1] || descriptions[1];
  };

  return (
    <>
      <div style={{ padding: '24px' }}>
        <Typography>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <Title level={1}>文章改写<TourGuideButton onClick={showTour} /></Title>
          </div>
          <Paragraph>
            对现有文章进行重写，保持原意但改变表达方式。选择不同的改写风格和程度，获得满意的改写结果。
          </Paragraph>
        </Typography>

        <Row gutter={[16, 16]}>
          <Col xs={24} md={12}>
            <Card title="文章输入与设置" size="small">
              <Form
                form={form}
                layout="vertical"
              >
                <Form.Item
                  label="原文内容"
                  name="originalContent"
                  rules={[{ required: true, message: '请输入需要改写的文章内容' }]}
                >
                  <div ref={originalContentRef}>
                    <TextArea
                      rows={8}
                      placeholder="请输入需要改写的文章内容"
                      maxLength={5000}
                      showCount
                    />
                  </div>
                </Form.Item>

                <Form.Item
                  label="改写风格"
                  name="rewritingStyle"
                  initialValue="professional"
                >
                  <div ref={styleRef}>
                    <Select
                      style={{ width: '100%' }}
                      onChange={handleStyleChange}
                      placeholder="请选择改写风格"
                    >
                      {rewritingStyles.map(style => (
                        <Option key={style.value} value={style.value}>
                          {style.label}
                        </Option>
                      ))}
                    </Select>
                  </div>
                </Form.Item>

                <div style={{ marginBottom: '16px' }}>
                  <Paragraph type="secondary" style={{ margin: 0 }}>
                    {getSelectedStyleDescription()}
                  </Paragraph>
                </div>

                <Form.Item
                  label="改写程度"
                  name="rewritingLevel"
                  initialValue={2}
                >
                  <div ref={levelRef}>
                    <InputNumber
                      min={1}
                      max={5}
                      onChange={handleLevelChange}
                      style={{ width: '100%' }}
                    />
                  </div>
                </Form.Item>

                <div style={{ marginBottom: '16px' }}>
                  <Paragraph type="secondary" style={{ margin: 0 }}>
                    {getLevelDescription()}
                  </Paragraph>
                </div>

                <Form.Item>
                  <Space direction="vertical" style={{ width: '100%' }} ref={rewriteButtonRef}>
                    <Button
                      type="primary"
                      onClick={handleSubmit}
                      loading={loading}
                      block
                    >
                      {loading ? '改写中...' : '开始改写'}
                    </Button>
                    {rewrittenContent && (
                      <Button
                        icon={<RedoOutlined />}
                        onClick={handleRewriteAgain}
                        loading={loading}
                        block
                      >
                        {loading ? '重新改写中...' : '重新改写'}
                      </Button>
                    )}
                  </Space>
                </Form.Item>
              </Form>
            </Card>
          </Col>

          <Col xs={24} md={12}>
            <Tabs defaultActiveKey="result">
              <TabPane tab="改写结果" key="result">
                <Card size="small" ref={resultRef}>
                  {loading ? (
                    <div style={{ textAlign: 'center', padding: '60px 0' }}>
                      <Spin size="large" />
                      <p style={{ marginTop: '16px' }}>正在进行文章改写，请稍候...</p>
                    </div>
                  ) : rewrittenContent ? (
                    <div>
                      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '16px' }}>
                        <Typography.Text type="secondary">
                          风格：{rewritingStyles.find(s => s.value === rewritingStyle)?.label} |
                          程度：{rewritingLevel}/5
                        </Typography.Text>
                        <Button
                          type="primary"
                          icon={<CopyOutlined />}
                          onClick={() => handleCopyContent(rewrittenContent)}
                        >
                          复制内容
                        </Button>
                      </div>
                      <TextArea
                        value={rewrittenContent}
                        rows={14}
                        readOnly
                        style={{ backgroundColor: '#fafafa' }}
                      />
                    </div>
                  ) : (
                    <div style={{ textAlign: 'center', padding: '60px 0', color: '#999' }}>
                      改写结果将显示在这里
                    </div>
                  )}
                </Card>
              </TabPane>
              <TabPane tab="改写历史" key="history">
                <Card size="small" ref={historyRef}>
                  {rewritingHistory.length > 0 ? (
                    <Space direction="vertical" style={{ width: '100%' }}>
                      {rewritingHistory.map((content, index) => (
                        <div
                          key={index}
                          style={{
                            padding: '12px',
                            border: '1px solid #e8e8e8',
                            borderRadius: '4px',
                            marginBottom: '8px',
                            position: 'relative',
                          }}
                        >
                          <TextArea
                            value={content}
                            rows={3}
                            readOnly
                            style={{ backgroundColor: '#fafafa', marginBottom: '8px' }}
                          />
                          <Button
                            type="link"
                            icon={<ArrowRightOutlined />}
                            onClick={() => handleUseHistory(content)}
                            style={{ position: 'absolute', bottom: '12px', right: '12px' }}
                          >
                            使用此内容
                          </Button>
                        </div>
                      ))}
                    </Space>
                  ) : (
                    <div style={{ textAlign: 'center', padding: '60px 0', color: '#999' }}>
                      暂无改写历史
                    </div>
                  )}
                </Card>
              </TabPane>
            </Tabs>
          </Col>
        </Row>
      </div>

      <CommonTour
        open={tourVisible}
        onClose={() => setTourVisible(false)}
        steps={tourSteps}
        targetRefs={tourRefs}
      />
    </>
  );
};

export default ArticleRewritingPage;